<template>
  <div class="dashboard-container">
    <!-- 欢迎信息 -->
    <div class="welcome-section card-shadow">
      <div class="welcome-content">
        <h1>欢迎回来，{{ userInfo.username || '用户' }}</h1>
        <p>{{ getGreeting() }} 今天是 {{ getCurrentDate() }}，祝您工作愉快！</p>
      </div>
      <div class="welcome-actions">
        <el-button type="success" icon="el-icon-plus" @click="quickAdd">快速添加产品</el-button>
        <el-dropdown trigger="click" @command="handleCommand">
          <el-button type="primary" plain icon="el-icon-more">
            更多操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="report">生成报表</el-dropdown-item>
            <el-dropdown-item command="export">导出数据</el-dropdown-item>
            <el-dropdown-item command="settings">系统设置</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>

    <!-- 数据概览卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card card-shadow" shadow="hover">
        <div class="stat-icon-wrapper green">
          <i class="el-icon-shopping-cart-full"></i>
        </div>
        <div class="stat-info">
          <div class="stat-title">本月订单</div>
          <div class="stat-value">
            <count-to :startVal="0" :endVal="orderStats.currentMonthOrders" :duration="2000"></count-to>
          </div>
          <div class="stat-trend" :class="orderTrend >= 0 ? 'up' : 'down'">
            <i :class="orderTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
            {{ orderStats.growthRate }}
          </div>
        </div>
      </el-card>

      <el-card class="stat-card card-shadow" shadow="hover">
        <div class="stat-icon-wrapper blue">
          <i class="el-icon-money"></i>
        </div>
        <div class="stat-info">
          <div class="stat-title">本月销售额</div>
          <div class="stat-value">
            ¥<count-to :startVal="0" :endVal="salesStats.currentMonthSales" :duration="2000" :decimals="2"></count-to>
          </div>
          <div class="stat-trend" :class="saleTrend >= 0 ? 'up' : 'down'">
            <i :class="saleTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
            {{ salesStats.growthRate }}
          </div>
        </div>
      </el-card>

      <el-card class="stat-card card-shadow" shadow="hover">
        <div class="stat-icon-wrapper orange">
          <i class="el-icon-user"></i>
        </div>
        <div class="stat-info">
          <div class="stat-title">本年用户数</div>
          <div class="stat-value">
            <count-to :startVal="0" :endVal="userStats.currentYearUsers" :duration="2000"></count-to>
          </div>
          <div class="stat-trend" :class="userTrend >= 0 ? 'up' : 'down'">
            <i :class="userTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
            {{ userStats.growthRate }}
          </div>
        </div>
      </el-card>

      <el-card class="stat-card card-shadow" shadow="hover">
        <div class="stat-icon-wrapper purple">
          <i class="el-icon-s-goods"></i>
        </div>
        <div class="stat-info">
          <div class="stat-title">农产品总数</div>
          <div class="stat-value">
            <count-to :startVal="0" :endVal="productStats.totalProducts" :duration="2000"></count-to>
          </div>
          <div class="stat-trend">
            <span>共{{ productStats.categories }}个品类</span>
          </div>
        </div>
      </el-card>
    </div>

    <div class="dashboard-content">
      <!-- 左侧图表区域 -->
      <div class="chart-section">
        <!-- 销售趋势图表 -->
        <el-card class="chart-card card-shadow" shadow="hover">
          <div slot="header" class="chart-header">
            <span>销售趋势分析</span>
            <div class="chart-actions">
              <el-radio-group v-model="salesChartPeriod" size="mini" @change="updateSalesChart">
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
                <el-radio-button label="year">年</el-radio-button>
              </el-radio-group>
              <el-button type="text" icon="el-icon-refresh" @click="refreshSalesChart"></el-button>
            </div>
          </div>
          <div class="chart-content">
            <div ref="salesTrendChart" class="chart"></div>
          </div>
        </el-card>

        <!-- 品类销售占比 -->
        <el-card class="chart-card card-shadow" shadow="hover">
          <div slot="header" class="chart-header">
            <span>品类销售占比</span>
            <el-button type="text" icon="el-icon-refresh" @click="fetchCategoryStats"></el-button>
          </div>
          <div class="chart-content">
            <div ref="categoryChart" class="chart"></div>
          </div>
        </el-card>
      </div>

      <!-- 右侧内容区域 -->
      <div class="side-section">
        <!-- 热销商品TOP5 -->
        <el-card class="side-card card-shadow" shadow="hover">
          <div slot="header" class="card-header">
            <span>热销商品 TOP5</span>
            <el-button type="text" icon="el-icon-refresh" @click="fetchTopProducts"></el-button>
          </div>
          <div class="top-products">
            <div v-for="(product, index) in topProducts" :key="product.id" class="product-item">
              <div class="product-rank" :class="'rank-' + (index + 1)">{{ index + 1 }}</div>
              <div class="product-info">
                <div class="product-name">{{ product.name }}</div>
                <div class="product-stats">
                  <span class="product-sales">销量: {{ product.sales }}</span>
                  <span class="product-price">¥{{ product.price }}</span>
                </div>
              </div>
              <div class="product-trend" :class="product.trend >= 0 ? 'up' : 'down'">
                {{ product.trend >= 0 ? '+' : '' }}{{ product.trend }}%
              </div>
            </div>
          </div>
        </el-card>

        <!-- 通知公告 -->
        <el-card class="side-card notice-card card-shadow" shadow="hover">
          <div slot="header" class="card-header">
            <span>通知公告</span>
            <el-button type="text" icon="el-icon-refresh" @click="fetchAnnouncements"></el-button>
          </div>
          <div class="notice-content">
            <el-timeline>
              <el-timeline-item 
                v-for="(notice, index) in announcements" 
                :key="index" 
                :timestamp="notice.time" 
                :type="getNoticeType(notice.type)">
                <div class="notice-item">
                  <h4>{{ notice.title }}</h4>
                  <p class="notice-text">{{ notice.content }}</p>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import CountTo from 'vue-count-to'
import * as echarts from 'echarts'
import Request from '@/utils/request.js'

export default {
  name: 'Dashboard',
  components: {
    CountTo
  },
  inject: ['userInfo'],
  data() {
    return {
      // 统计数据
      orderStats: {
        currentMonthOrders: 256,
        lastMonthOrders: 220,
        growthRate: '16.36%'
      },
      salesStats: {
        currentMonthSales: 128500.75,
        lastMonthSales: 115200.50,
        growthRate: '11.54%'
      },
      userStats: {
        currentYearUsers: 1256,
        lastYearUsers: 980,
        growthRate: '28.16%'
      },
      productStats: {
        totalProducts: 328,
        categories: 12
      },
      // 图表相关
      salesChartPeriod: 'month',
      salesTrendChart: null,
      categoryChart: null,
      // 热销商品
      topProducts: [
        { id: 1, name: '有机红富士苹果', sales: 1280, price: 15.8, trend: 12.5 },
        { id: 2, name: '黑猪五花肉', sales: 980, price: 32.5, trend: 8.3 },
        { id: 3, name: '东北大米', sales: 860, price: 39.9, trend: -2.1 },
        { id: 4, name: '新鲜牛奶', sales: 750, price: 6.5, trend: 5.8 },
        { id: 5, name: '有机蔬菜套装', sales: 680, price: 45.0, trend: 15.2 }
      ],
      // 通知公告
      announcements: [
        { title: '系统升级通知', content: '系统将于本周六凌晨2点进行升级维护，预计持续2小时', time: '2023-06-15', type: 'warning' },
        { title: '新功能上线', content: '农产品金融模块已上线，欢迎使用', time: '2023-06-10', type: 'success' },
        { title: '促销活动', content: '夏季农产品促销活动即将开始，请做好准备', time: '2023-06-05', type: 'info' }
      ],
      // 图表数据
      salesData: {
        week: {
          dates: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          values: [12500, 13200, 10100, 13400, 19000, 23400, 21300]
        },
        month: {
          dates: ['1月', '2月', '3月', '4月', '5月', '6月'],
          values: [83500, 78200, 98100, 103400, 119000, 128500]
        },
        year: {
          dates: ['2018', '2019', '2020', '2021', '2022', '2023'],
          values: [580000, 680000, 770000, 930000, 1150000, 1285000]
        }
      },
      categoryData: [
        { value: 35, name: '蔬菜水果' },
        { value: 25, name: '肉禽蛋奶' },
        { value: 15, name: '粮油调味' },
        { value: 10, name: '水产海鲜' },
        { value: 15, name: '其他' }
      ]
    }
  },
  computed: {
    // 计算订单增长率数值（去掉百分号）
    orderTrend() {
      return parseFloat(this.orderStats.growthRate);
    },
    // 计算销售额增长率数值
    saleTrend() {
      return parseFloat(this.salesStats.growthRate);
    },
    // 计算用户增长率数值
    userTrend() {
      return parseFloat(this.userStats.growthRate);
    }
  },
  mounted() {
    this.initCharts();
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    if (this.salesTrendChart) {
      this.salesTrendChart.dispose();
    }
    if (this.categoryChart) {
      this.categoryChart.dispose();
    }
  },
  methods: {
    // 获取问候语
    getGreeting() {
      const hour = new Date().getHours();
      if (hour < 6) return '凌晨好！';
      if (hour < 9) return '早上好！';
      if (hour < 12) return '上午好！';
      if (hour < 14) return '中午好！';
      if (hour < 17) return '下午好！';
      if (hour < 19) return '傍晚好！';
      return '晚上好！';
    },
    // 获取当前日期
    getCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const day = now.getDate();
      const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      const weekday = weekdays[now.getDay()];
      return `${year}年${month}月${day}日 ${weekday}`;
    },
    // 初始化图表
    initCharts() {
      this.$nextTick(() => {
        this.initSalesTrendChart();
        this.initCategoryChart();
      });
    },
    // 初始化销售趋势图表
    initSalesTrendChart() {
      this.salesTrendChart = echarts.init(this.$refs.salesTrendChart);
      this.updateSalesChart();
    },
    // 更新销售趋势图表
    updateSalesChart() {
      const data = this.salesData[this.salesChartPeriod];
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.dates,
          axisLine: {
            lineStyle: {
              color: '#909399'
            }
          },
          axisLabel: {
            color: '#606266'
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisLabel: {
            color: '#606266'
          },
          splitLine: {
            lineStyle: {
              color: '#ebeef5'
            }
          }
        },
        series: [
          {
            name: '销售额',
            type: 'bar',
            barWidth: '60%',
            data: data.values,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#4caf50' },
                { offset: 1, color: '#81c784' }
              ])
            }
          }
        ]
      };
      this.salesTrendChart.setOption(option);
    },
    // 初始化品类销售占比图表
    initCategoryChart() {
      this.categoryChart = echarts.init(this.$refs.categoryChart);
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: this.categoryData.map(item => item.name),
          textStyle: {
            color: '#606266'
          }
        },
        series: [
          {
            name: '销售占比',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '12',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: this.categoryData,
            itemStyle: {
              borderRadius: 4,
              borderColor: '#fff',
              borderWidth: 2
            }
          }
        ],
        color: ['#4caf50', '#2196f3', '#ff9800', '#9c27b0', '#607d8b']
      };
      this.categoryChart.setOption(option);
    },
    // 刷新销售图表
    refreshSalesChart() {
      // 这里可以添加获取最新数据的逻辑
      this.updateSalesChart();
    },
    // 获取品类统计数据
    fetchCategoryStats() {
      // 这里可以添加从API获取数据的逻辑
      // 模拟API请求
      setTimeout(() => {
        this.initCategoryChart();
      }, 500);
    },
    // 获取热销商品数据
    fetchTopProducts() {
      // 这里可以添加从API获取数据的逻辑
      // 模拟API请求
      setTimeout(() => {
        // 模拟数据更新
        this.topProducts = [...this.topProducts];
      }, 500);
    },
    // 获取通知公告
    fetchAnnouncements() {
      // 这里可以添加从API获取数据的逻辑
      Request.get("/notice/limit", {
        params: {
          count: 5
        }
      }).then(response => {
        if (response.code === '0') {
          this.announcements = response.data;
        }
      }).catch(() => {
        // 模拟数据，如果API请求失败
        setTimeout(() => {
          // 保持当前数据不变
        }, 500);
      });
    },
    // 根据通知类型获取图标类型
    getNoticeType(type) {
      const typeMap = {
        'info': 'info',
        'warning': 'warning',
        'success': 'success',
        'error': 'danger'
      };
      return typeMap[type] || 'info';
    },
    // 快速添加
    quickAdd() {
      this.$router.push('/products/add');
    },
    // 处理下拉菜单命令
    handleCommand(command) {
      if (command === 'report') {
        this.$message.success('正在生成报表，请稍候...');
      } else if (command === 'export') {
        this.$message.success('数据导出功能即将上线');
      } else if (command === 'settings') {
        this.$router.push('/settings');
      }
    },
    // 调整图表大小
    resizeCharts() {
      if (this.salesTrendChart) {
        this.salesTrendChart.resize();
      }
      if (this.categoryChart) {
        this.categoryChart.resize();
      }
    }
  }
}
</script>

<style lang="less" scoped>
.dashboard-container {
  padding: 0;
  height: 100%;
  color: #333;
}

/* 欢迎区域 */
.welcome-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  
  .welcome-content {
    h1 {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin: 0 0 8px 0;
    }
    
    p {
      font-size: 14px;
      color: #606266;
      margin: 0;
    }
  }
  
  .welcome-actions {
    display: flex;
    gap: 12px;
  }
}

/* 统计卡片 */
.stat-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 24px;
  
  .stat-card {
    border-radius: 8px;
    display: flex;
    align-items: center;
    padding: 20px;
    transition: transform 0.3s;
    background-color: #fff;
    border: none;
    
    &:hover {
      transform: translateY(-5px);
    }
  }
  
  .stat-icon-wrapper {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    
    i {
      font-size: 30px;
      color: #fff;
    }
    
    &.green {
      background: linear-gradient(135deg, #4caf50, #2e7d32);
    }
    
    &.blue {
      background: linear-gradient(135deg, #2196f3, #1565c0);
    }
    
    &.orange {
      background: linear-gradient(135deg, #ff9800, #ef6c00);
    }
    
    &.purple {
      background: linear-gradient(135deg, #9c27b0, #6a1b9a);
    }
  }
  
  .stat-info {
    flex: 1;
  }
  
  .stat-title {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
  }
  
  .stat-value {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 8px;
  }
  
  .stat-trend {
    font-size: 12px;
    
    &.up {
      color: #4caf50;
    }
    
    &.down {
      color: #f56c6c;
    }
    
    i {
      margin-right: 4px;
    }
  }
}

/* 内容区域 */
.dashboard-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  height: calc(100% - 170px);
}

/* 图表区域 */
.chart-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
  
  .chart-card {
    flex: 1;
    border-radius: 8px;
    background-color: #fff;
    border: none;
    
    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .chart-actions {
        display: flex;
        align-items: center;
        gap: 10px;
      }
    }
    
    .chart-content {
      height: calc(100% - 30px);
      
      .chart {
        height: 100%;
        width: 100%;
      }
    }
  }
}

/* 侧边区域 */
.side-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
  
  .side-card {
    flex: 1;
    border-radius: 8px;
    overflow: hidden;
    background-color: #fff;
    border: none;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .top-products {
    .product-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f2f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .product-rank {
        width: 24px;
        height: 24px;
        border-radius: 4px;
        background-color: #f5f7fa;
        color: #909399;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        margin-right: 12px;
      }
      
      .rank-1 {
        background-color: #f44336;
        color: #fff;
      }
      
      .rank-2 {
        background-color: #ff9800;
        color: #fff;
      }
      
      .rank-3 {
        background-color: #4caf50;
        color: #fff;
      }
      
      .product-info {
        flex: 1;
        
        .product-name {
          font-size: 14px;
          color: #303133;
          margin-bottom: 4px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        
        .product-stats {
          font-size: 12px;
          color: #909399;
          display: flex;
          justify-content: space-between;
        }
      }
      
      .product-trend {
        font-size: 12px;
        font-weight: bold;
        
        &.up {
          color: #4caf50;
        }
        
        &.down {
          color: #f56c6c;
        }
      }
    }
  }
  
  .notice-card {
    .notice-content {
      max-height: 100%;
      overflow-y: auto;
      
      .notice-item {
        h4 {
          margin: 0 0 8px 0;
          font-size: 14px;
          color: #303133;
        }
        
        .notice-text {
          margin: 0;
          font-size: 12px;
          color: #606266;
          line-height: 1.6;
        }
      }
    }
  }
}

@media (max-width: 1200px) {
  .stat-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .dashboard-content {
    grid-template-columns: 1fr;
    height: auto;
  }
}

@media (max-width: 768px) {
  .welcome-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .stat-cards {
    grid-template-columns: 1fr;
  }
}
</style> 